package com.jiezhuo.controller;

import com.jiezhuo.config.Config;
import com.jiezhuo.entity.ShardingFile;
import com.jiezhuo.interfaceEntity.Rediskey;
import com.jiezhuo.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


@Api(tags = "文件上传")
@RestController
@RequestMapping("fileUpload")
public class FileUpload {
    @Autowired
    Config config;
    @PostMapping("delFile")
    public R delFile(String path) throws IOException {
        String url = config.getPath();

        File file = new File(path);
        System.out.println(file.getAbsolutePath());
        if (file.exists()) file.delete();
        return R.ok().msg("删除成功");
    }

    @PostMapping("getFiles")
    public  List<String> getAllFile(String directoryPath, boolean isAddDirectory) {
        String url = config.getPath();
        List<String> list = new ArrayList<>();
        File baseFile = new File(url +System.getProperty("file.separator")+directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if(isAddDirectory){
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getAllFile(file.getAbsolutePath().substring(url.length()),isAddDirectory));
            } else {

                list.add(file.getAbsolutePath().substring(url.length()));
            }
        }
        return list;
    }


    @PostMapping("upload")
    public R uploadFile(MultipartFile file,String path) throws IOException {
        String url = config.getPath();
        File f = new File(url +System.getProperty("file.separator")+path);
        String fix = file.getOriginalFilename();
        if(fix.contains(".")){
            fix = fix.split("\\.")[1];
        }
        String urlPath=System.getProperty("file.separator")+path+System.getProperty("file.separator")+(System.currentTimeMillis()+"").substring(5,10)+"."+fix;
        File pathUrl = new File(url+urlPath);
        if(!pathUrl.exists()){
            boolean mkdir = pathUrl.mkdirs();
        }
        file.transferTo(pathUrl);
        return R.ok().msg("上传成功").data("url",urlPath);
    }



//    @Rediskey(time = 1,redisKey = "videoUpload")
    @PostMapping("videoUpload")
    public R videoUpload(String name,MultipartFile file,long size,long index) throws IOException {

        String url = config.getPath();
        String fix = file.getOriginalFilename();
        if(fix.contains(".")){
            fix = fix.split("\\.")[1];
        }
        byte[] bytes1 = file.getBytes();

        InputStream inputStream = file.getInputStream();


        String urlPath=System.getProperty("file.separator")+"test"+"."+fix;

        File videoFile  = new File(url+urlPath);
        OutputStream bos=null;//输出流用于输出分片文件至磁盘
        if (!videoFile.exists()&&index==0)//文件是否已经创建且文件是第一个保证文件的顺须
        {
//            long splitSize=5*1024*1024;//单片文件大小,5M
//            long writeByte=0;//已读取的字节数
//            int len=0;
//            byte[] bt=new byte[1024];
//            len=inputStream.read(bt);
//
//                if(writeByte%splitSize==0){
//                    if(bos!=null){
//                        bos.flush();
//                        bos.close();
//                    }
//                    bos=new BufferedOutputStream(new FileOutputStream(url+urlPath));
////                    bos=new BufferedOutputStream(new FileOutputStream(filePath+"."+(writeByte/splitSize+1)+".part"));
//                }
//
//                bos.write(bt, 0, len);
//            bos.flush();
//            bos.close();


            file.transferTo(videoFile);//如果没有就创建
            return R.ok().msg("分片0创建成功");
        }else {
            RandomAccessFile raf = new RandomAccessFile(videoFile,"rw");
            raf.seek(index*size);//seek（int n）从n处处理
            byte[] bytes =file.getBytes();//提区文件的字节流
            raf.write(bytes);//上面的seek方法已经把指针放在这里从这直接写入
            raf.close();//写入后关闭


        }
        return R.ok().msg("分片"+index+"上传视频成功").data("index",index).data("url","");
    }
}
